﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace UCL.Data
{
    public class DBUpdateHelper
    {
        /// <summary>
        /// 升级数据表
        /// </summary>
        /// <param name="updateSqlText">如：AppRes.ResourceManager.GetString("tblName_update")</param>
        /// <returns></returns>
        /// <remarks>2014-4-25 by sutroon</remarks>
        public string UpdateDB(string updateSqlText)
        {
            using (SqlConnection conn = new SqlConnection())
            {
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandText = string.Format("select Version from tSystem where TableName=''");
                try
                {
                    conn.Open();
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                string ver = string.Empty;
                try
                {
                    using (SqlDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            ver = dr[0] == DBNull.Value ? string.Empty : dr[0].ToString();
                        }
                    }

                }
                catch (Exception ex)
                {
                    ver = "1.0.0.0"; // 2014.4.25.1
                    cmd.CommandText = "insert into aa ()";
                    cmd.ExecuteNonQuery();
                }
                //string verLoc=AppRes.ResourceManager.GetString("").ToLine()[0];
                string verLoc = "";
                if (CompareVersion(ver, verLoc))
                {
                    string scripts = updateSqlText;
                    scripts = scripts.Substring(scripts.IndexOf("#[" + verLoc + "]") + 1);

                    scripts = System.Text.RegularExpressions.Regex.Replace(scripts, "#[\\.]", "");
                    cmd.CommandText = scripts;
                    cmd.ExecuteNonQuery();
                }
            }
            return "SUCCESS";
        }
        public bool CompareVersion(string verNew, string verOld)
        {
            return true;
        }
    }
}
